﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using AhCha.Fortunate.Common.Utility;
using AhCha.Fortunate.ModelsDto;

namespace AhCha.Fortunate.Api.Controllers
{
    /// <summary>
    /// BaseApiController，所有新增或生成的Controller都应该继承BaseApiController
    /// 且定义api后，【禁止瞎几把乱改接口名】导致对接接口404
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要验证token
    public class BaseApiController : ControllerBase
    {
        /// <summary>
        /// 获取月的天数
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <returns></returns>
        protected int MonthDays(int year, int month)
        {
            switch (month)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    return 31;
                case 2:
                    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                        return 29;//闰年
                    else
                        return 28;
                default:
                    return 30;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskId">线程id</param>
        /// <param name="item">数据</param>
        /// <returns></returns>
        protected string GetTaskName(string taskId, string item)
        {
            return $"线程id：{taskId} -Value-{item} -Text-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
        }
        
        /// <summary>
        /// 当前时间戳
        /// </summary>
        protected long GetTimestamp => DateTimeOffset.UtcNow.ToUnixTimeSeconds();

        /// <summary>
        /// 获取系统动态Aes密钥（每天定时生成）
        /// </summary>
        /// <returns></returns>
        protected string GetDynamicAesKey => GenerateKey.GetAesKey;

        /// <summary>
        /// 输出成功提示信息
        /// </summary>
        /// <returns></returns>
        protected ResponseOutput Success(string Message = "")
        {
            return ResponseOutput.Correct(Message);
        }

        /// <summary>
        /// 输出数据
        /// </summary>
        /// <param name="Data">List/object</param>
        /// <returns></returns>
        protected ResponseOutput Success(object Data)
        {
            return ResponseOutput.Correct(Data);
        }

        /// <summary>
        /// 输出数据 + 提示信息
        /// </summary>
        /// <param name="Data">List/object</param>
        /// <param name="Message">提示信息</param>
        /// <returns></returns>
        protected ResponseOutput Success(object Data, string Message)
        {
            return ResponseOutput.Correct(Data, Message);
        }

        /// <summary>
        /// 输出失败提示信息
        /// </summary>
        /// <param name="Message">错误提示信息</param>
        /// <returns></returns>
        protected ResponseOutput Fail(string? Message = null)
        {
            return ResponseOutput.Mistake(Message);
        }


        /// <summary>
        /// 文件链接转 IFormFile
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<IFormFile> UrlToFormFileAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                // 下载图片数据
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();

                // 获取文件名
                string fileName = Path.GetFileName(url);

                // 创建 MemoryStream 来保存图片数据
                using (var memoryStream = new MemoryStream(imageBytes))
                {
                    // 创建 FormFile
                    var formFile = new FormFile(memoryStream, 0, imageBytes.Length, "image", fileName);
                    formFile.Headers = new HeaderDictionary();
                    formFile.ContentType = "image/jpeg"; // 根据需要设置正确的 MIME 类型

                    return formFile;
                }
            }
        }

        /// <summary>
        /// 文件转byte[]
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        protected async Task<byte[]> ConvertFormFileToBytes(IFormFile formFile)
        {
            if (formFile == null || formFile.Length == 0)
            {
                return null;
            }

            using (var memoryStream = new MemoryStream())
            {
                await formFile.CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }
    
    
    }

    /// <summary>
    /// 定义js函数，由服务器端调用，前端实现
    /// </summary>
    public class SendMethod
    {
        /// <summary>
        /// 测试是否可正常调用js函数
        /// </summary>
        public const string ReceiveMessage = "ReceiveMessage";

    }
}
